﻿using HuiZe.education.Model;
using HuiZe.education.Resource.Controls;
using HuiZe.education.ViewModel;
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Reflection;
using Spire.Presentation;
using System.IO;
using HuiZe.education.Common;
using Label = System.Windows.Controls.Label;

namespace HuiZe.education.View
{
    /// <summary>
    /// BeginClass26.xaml 的交互逻辑
    /// </summary>
    public partial class BeginClass26 : Window
    {
        public BeginClass26()
        {
            InitializeComponent();
            //var w = new WebBrowserOverlay(this.BdBrowser);
            //var wb = w.WebBrowser;
            //var HelpUrl = "file:\\I:\\wpf_jz111\\huize-edu\\HuiZeOutPut\\ConvertHtmls\\191d0de1296c1c3b1ca34c773c3582df.html";
            //wb.Navigate(new System.Uri(HelpUrl));
            Loaded += ResourceView_Loaded;


        }
        public AttendClassViewModel attendClassView { get; set; }
        public string BkType { get; set; }
        public string BkId { get; set; }
        public ObservableCollection<ResourceCenterModel> resources { get; set; }

        private void ResourceView_Loaded(object sender, RoutedEventArgs e)
        {

            //webBrowser0 = new WebBrowser();
            //webBrowser0.ScriptErrorsSuppressed = true;
            attendClassView = DataContext as AttendClassViewModel;
            var beginResList = attendClassView.GetClassResourceDetail(BkId);
            if (beginResList != null)
            {
                resList.Children.Clear();
                foreach (var item in beginResList)
                {
                    PlayBookControl playBook = new PlayBookControl
                    {

                        SourceUrl = item.file,
                        Imageurl = item.image_cover,
                        Imagetxt = item.bname,
                        Width =371,
                        Height = 70,
                        Margin = new Thickness(5,5,0,0),


                    };
                    //playBook.ImageButton.SourceUrl = item.file;
                    playBook.PreviewMouseUp += customButton_Click;
                    //CustomButton customButton = new CustomButton()
                    //{
                    //    Template = (ControlTemplate)FindResource("HZImageButtonTemplate"),
                    //    ImageSource = new BitmapImage(new Uri(item.image_cover)),
                    //    SourceUrl = item.file,
                    //    //MeadiaType
                    //    Content = item.bname,
                    //    Width = 80,
                    //    Height = 40,
                    //    Margin = new Thickness(0, 20, 10, 0),
                    //};
                    //Label label = new Label
                    //{
                    //    Content = item.bname,
                    //    Margin = new Thickness(0, 20, 10, 0),
                    //};
                    //customButton.Click += customButton_Click;


                    resList.Children.Add(playBook);
                    //resList.Children.Add(label);


                }


            }




        }


        private void customButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            PlayBookControl customButton = sender as PlayBookControl;
            //string preUrl = "https://ow365.cn/?i=28004&ssl=1&n=5&furl=";
            string url = customButton.SourceUrl;
            //MediaPlayBorder.Children.Clear();


            if (url.ToString().Contains("jpg") || url.ToString().Contains("png"))
            {

                string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");

                //pageContent.Content = f2;
                videoPgae.Visibility = Visibility.Visible;
                otherPgae.Visibility = Visibility.Collapsed;
                mediaElement.Source = new Uri(LocalPath);
                mediaElement.Play();
                //webBrowser11.Navigate("file:\\" + LocalPath);
            }
            else if (url.ToString().Contains("mp3") || url.ToString().Contains("mp4") || url.ToString().Contains("wav") )
            {
                string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");

                //pageContent.Content = f2;
                videoPgae.Visibility = Visibility.Visible;
                otherPgae.Visibility = Visibility.Collapsed;
                mediaElement.Source = new Uri(LocalPath);
                mediaElement.Play();



            }
            else if (url.ToString().Contains("ppts") || url.ToString().Contains("ppt"))
            {
                //videoPgae.Visibility = Visibility.Collapsed;
                //otherPgae2.Visibility = Visibility.Visible;
               
                //string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\"); ;
                ////pageContent.Content = f1;
                //PptPlay.Height = otherPgae.Height;
                //PptPlay.Width = otherPgae.Width;
                //PptPlay.PdfUrl = LocalPath;
                //PptPlay.PlayPPt2();
                //OpenSourceFile(LocalPath);


            }
            //else if (url.ToString().Contains("pdf") || url.ToString().Contains("swf") || url.ToString().Contains("flash"))
            else if (url.ToString().Contains("swf") || url.ToString().Contains("flash"))
            {
                //string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");
                //PdfPgae.Visibility = Visibility.Visible;
                //videoPgae.Visibility = Visibility.Collapsed;
                //otherPgae.Visibility = Visibility.Collapsed;
                //moonPdfPanel.OpenFile(LocalPath);

                string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");

                //pageContent.Content = f2;
                videoPgae.Visibility = Visibility.Visible;
                otherPgae.Visibility = Visibility.Collapsed;
                mediaElement.Source = new Uri(LocalPath);
                mediaElement.Play();


            }
            else if (url.ToString().Contains("doc") || url.ToString().Contains("docx"))
            {
                string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");
                videoPgae.Visibility = Visibility.Collapsed;
                otherPgae.Visibility = Visibility.Visible;
                documentViewer1.Height = otherPgae.Height;
                documentViewer1.Width = otherPgae.Width;
                OpenSourceFile(LocalPath);


            }
            else if (url.ToString().Contains("xlsx") || url.ToString().Contains("xls"))
            {
                string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");
                videoPgae.Visibility = Visibility.Collapsed;
                otherPgae.Visibility = Visibility.Visible;
                documentViewer1.Height = otherPgae.Height;
                documentViewer1.Width = otherPgae.Width;
                OpenSourceFile(LocalPath);

            }
            else
            {



            }


        }


        private void close_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //webBrowser11.Navigate("");
            this.Close();
        }



        private void SourceTree_PreviewMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {


        }










        private string DownLoadFile(string url, string savepath)
        {
            string extention = Path.GetExtension(url);
            string FileName = Path.GetFileNameWithoutExtension(url);
            string downloadpath = savepath + "\\" + FileName + extention;
            WebApiHelper.Download(url, downloadpath);

            return downloadpath;


        }


        private void exitAddStu_Click(object sender, RoutedEventArgs e)
        {


        }

        System.Windows.Xps.Packaging.XpsDocument xpsDoc;
        public static bool officeFileOpen_Status = false;
        private void OpenSourceFile(string FilePath)
        {

            string xpsFilePath = string.Empty;

            var convertResults = OfficeToXps.ConvertToXps(FilePath, ref xpsFilePath);
            switch (convertResults.Result)
            {
                case ConversionResult.OK:
                    xpsDoc = new System.Windows.Xps.Packaging.XpsDocument(xpsFilePath, FileAccess.Read);
                    documentViewer1.Document = xpsDoc.GetFixedDocumentSequence();
                    officeFileOpen_Status = true;
                    break;

                case ConversionResult.InvalidFilePath:
                    // Handle bad file path or file missing
                    break;
                case ConversionResult.UnexpectedError:
                    // This should only happen if the code is modified poorly
                    break;
                case ConversionResult.ErrorUnableToInitializeOfficeApp:
                    // Handle Office 2007 (Word | Excel | PowerPoint) not installed
                    break;
                case ConversionResult.ErrorUnableToOpenOfficeFile:
                    // Handle source file being locked or invalid permissions
                    break;
                case ConversionResult.ErrorUnableToAccessOfficeInterop:
                    // Handle Office 2007 (Word | Excel | PowerPoint) not installed
                    break;
                case ConversionResult.ErrorUnableToExportToXps:
                    // Handle Microsoft Save As PDF or XPS Add-In missing for 2007
                    break;
            }
        }


        // 预览ppt（使用Presentation插件）
        /// <summary>
        /// ppt转html
        /// </summary>
        /// <returns></returns>
        public string PptToHtml(string url, string savepath)
        {
            var resultUrl = string.Empty;
            var serverUrl = string.Empty;
            string extention = Path.GetExtension(url);
            string FileName = Path.GetFileNameWithoutExtension(url);
            string htmlName = Path.GetFileNameWithoutExtension(url) + ".html";
            String outputFile = Path.GetDirectoryName(savepath) + "\\" + htmlName;
            //实例化Presentation类，加载文件
            Spire.Presentation.Presentation ppt = new Spire.Presentation.Presentation();
            try
            {
                string downloadpath = savepath + "\\" + FileName + extention;
                WebApiHelper.Download(url, downloadpath);

                ppt.LoadFromFile(downloadpath);
                ppt.SaveToFile(outputFile, FileFormat.Html);

                //打开文件

                //保存文件为HTML

            }//`在这里插入代码片`
            catch (Exception ex)
            {
                //this.Write(ex);
            }
            //得到返回的html地址
            resultUrl = Path.GetDirectoryName(savepath) + "\\" + htmlName;
            var lastUrl = Path.GetFileName(resultUrl);
            //resultUrl = ConfigurationManager.AppSettings["ResultUrl"] + lastUrl;
            //serverUrl = ConfigurationManager.AppSettings["ServerUrl"];
            return outputFile;


        }
    }
}
